/**
  ******************************************************************************
  * File Name          : main.c
  * Description        : Main program body
  ******************************************************************************
  *
  * COPYRIGHT(c) 2017 STMicroelectronics
  *
  * Redistribution and use in source and binary forms, with or without modification,
  * are permitted provided that the following conditions are met:
  *   1. Redistributions of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  *   2. Redistributions in binary form must reproduce the above copyright notice,
  *      this list of conditions and the following disclaimer in the documentation
  *      and/or other materials provided with the distribution.
  *   3. Neither the name of STMicroelectronics nor the names of its contributors
  *      may be used to endorse or promote products derived from this software
  *      without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f1xx_hal.h"

/* USER CODE BEGIN Includes */
#include "stdio.h"

#include "4032.h"

#include "CY8CMBR3xxx_APIs.h"
/* USER CODE END Includes */

/* Private variables ---------------------------------------------------------*/
//I2C_HandleTypeDef hi2c1;
UART_HandleTypeDef huart1;

/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
uint8_t buffer[20];
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void Error_Handler(void);
static void MX_GPIO_Init(void);
static void MX_I2C1_Init(void);
static void MX_USART1_UART_Init(void);

/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/

/* USER CODE END PFP */

/* USER CODE BEGIN 0 */
int fputc(int ch,FILE *f)
{
	uint8_t temp[1]={ch};
	HAL_UART_Transmit(&huart1,temp,1,2);
	return(ch);
}


unsigned char configData2[128] = {
    0xFF, 0x7F, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00,
    0xFF, 0xFF, 0xFF, 0x3F, 0xC8, 0xC8, 0xC8, 0xC8,
    0x96, 0x96, 0x96, 0x96, 0x96, 0x96, 0x96, 0xC8,
    0xC8, 0xC8, 0xC8, 0x7F, 0x03, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
    0x05, 0x00, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x1E, 0x00,
    0x00, 0x1E, 0x1E, 0x00, 0x00, 0x00, 0x01, 0x01,
    0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0x00, 0x00, 0x00, 0x04, 0x03, 0x01, 0x50,
    0x00, 0x37, 0x06, 0x00, 0x00, 0x0A, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0xA8
};



unsigned char tp_int = 0;
unsigned char tp_rcv_h = 0;
unsigned char tp_rcv_l = 0;
unsigned char tp_dump = 0;
unsigned char tp_tmp[128];

#define TP_ADDR 0x6e
uint8 tpIsInitialized = 0;
/* USER CODE END 0 */

int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration----------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* Configure the system clock */
  SystemClock_Config();

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C1_Init();
  MX_USART1_UART_Init();

  /* USER CODE BEGIN 2 */
	//HAL_NVIC_DisableIRQ(EXTI9_5_IRQn);
	
	/*HAL_GPIO_WritePin(EN_VDDOUT_GPIO_Port, EN_VDDOUT_Pin, GPIO_PIN_RESET);
	HAL_Delay(100);
	HAL_GPIO_WritePin(EN_VDDOUT_GPIO_Port, EN_VDDOUT_Pin, GPIO_PIN_SET);
	HAL_Delay(100);
	HAL_GPIO_WritePin(EN_VDDOUT_GPIO_Port, EN_VDDOUT_Pin, GPIO_PIN_RESET);
	HAL_Delay(200);*/
	
	HAL_GPIO_WritePin(EN_VDDOUT_GPIO_Port, EN_VDDOUT_Pin, GPIO_PIN_RESET);
	HAL_Delay(200);
	HAL_NVIC_EnableIRQ(EXTI9_5_IRQn);
	HAL_Delay(800);
	printf("\r\n");
	printf("HAL initialized\r\n");
	
	
	
	/*******************
	lcd init
	**********************/
	
	PCF8576_INIT initStruct;
	initStruct.slaveAddr = 0x70;
	initStruct.mode_set = 0x48;
	initStruct.load_data_pointer = 0x80;
	initStruct.device_select = 0xe1;
	initStruct.bank_select = 0xf8;
	initStruct.blink_select = 0xf0;
	
	for(uint16_t i = 0; i<20; i++) {
		buffer[i] = 0xaa;
	}
	
	
	
	/*******************
	tp init
	**********************/
	
	
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */
  
  

	
	
	
	
	i4032LcdTest(&hi2c1, initStruct, buffer);
	
	/*******************
	tp test
	**********************/
	while (TRUE == CY8CMBR3xxx_Configure(TP_ADDR, configData2)) {
		i4032preTpTest(&hi2c1, initStruct, buffer);
		
		uint8 prevProximityStatus = 0x00;
		bool tp_status = FALSE;
		//CY8CMBR3xxx_SENSORSTATUS tp_regstatus;
		CY8CMBR3xxx_SENSORSTATUS sensorStatus;
		//uint8 writeGPOOutputState[2] = {CY8CMBR3xxx_GPO_OUTPUT_STATE, 0x00};

		while(1) {
			if(tp_int) {
				
				//CY8CMBR3xxx_Configure(TP_ADDR, configData2);
				
				printf("Int IN\r\n");
				//HAL_Delay(100);
				
				uint16_t tpTimeOut = 0x4ff;
				uint8 tpValid = 0;
				while(tpTimeOut){
					tpTimeOut--;
					
					tp_status = CY8CMBR3xxx_VerifyDeviceOnBus(TP_ADDR);
					
					if(tp_status == TRUE) {
						tpTimeOut = 0;
						tpValid = 1;
					}
				}
				
				
				if( tpValid == 1 ){
					CY8CMBR3xxx_ReadSensorStatus(TP_ADDR, &sensorStatus);
				//if(TRUE == CY8CMBR3xxx_ReadSensorStatus(TP_ADDR, &sensorStatus)) {
					HAL_Delay(50);
					//tp_status = CY8CMBR3xxx_ReadSensorStatus(TP_ADDR, &sensorStatus);
					uint16_t button = sensorStatus.buttonStatus;
					//uint16_t button = sensorStatus.latchedButtonStatus;
					uint16_t butTemp = button&0x00ff;
					button >>= 8;
					button += butTemp<<8;
					if(button) {
						printf("%02x,%02x    DOWN\r\n",0xff&(button>>8), 0xff&button);
					} else {
						printf("         UP\r\n");
					}
					
					
					switch (button) {
						case (1<<0):	//0001
							for(unsigned char i = 18; i <= 21; i++) {
								for(unsigned char j = 0; j < 4; j++) {
									pcf8576_drawPixel(&hi2c1, initStruct, buffer, i, j, 0);
								}
							}
						break;
						
						case (1<<1):	//0002
							for(unsigned char i = 14; i <= 17; i++) {
								for(unsigned char j = 0; j < 4; j++) {
									pcf8576_drawPixel(&hi2c1, initStruct, buffer, i, j, 0);
								}
							}
						break;
						
						case (1<<2):	//0004
							for(unsigned char i = 6; i <= 13; i++) {
								for(unsigned char j = 0; j < 4; j++) {
									pcf8576_drawPixel(&hi2c1, initStruct, buffer, i, j, 0);
								}
							}
						break;
						
						case (1<<3):	//0008
							for(unsigned char i = 2; i <= 3; i++) {
								for(unsigned char j = 0; j < 4; j++) {
									pcf8576_drawPixel(&hi2c1, initStruct, buffer, i, j, 0);
								}
							}
						break;
						
						case (1<<4):	//0010
							for(unsigned char i = 4; i <= 4; i++) {
								for(unsigned char j = 0; j < 4; j++) {
									pcf8576_drawPixel(&hi2c1, initStruct, buffer, i, j, 0);
								}
							}
						break;
						
						case (1<<5):	//0020
							for(unsigned char i = 39; i <= 39; i++) {
								for(unsigned char j = 0; j < 4; j++) {
									pcf8576_drawPixel(&hi2c1, initStruct, buffer, i, j, 0);
								}
							}
						break;
						
						case (1<<6):	//0040
							for(unsigned char i = 38; i <= 38; i++) {
								for(unsigned char j = 0; j < 4; j++) {
									pcf8576_drawPixel(&hi2c1, initStruct, buffer, i, j, 0);
								}
							}
						break;
						
						case (1<<7):	//0080
							//pcf8576_drawPixel(&hi2c1, initStruct, buffer, 4, 3, 1);
						break;
						
						case (1<<8):	//0100
							pcf8576_drawPixel(&hi2c1, initStruct, buffer, 34, 0, 0);
							pcf8576_drawPixel(&hi2c1, initStruct, buffer, 34, 1, 0);
							pcf8576_drawPixel(&hi2c1, initStruct, buffer, 34, 2, 0);
						break;
						
						case (1<<9):	//0200
							pcf8576_drawPixel(&hi2c1, initStruct, buffer, 35, 0, 0);
							pcf8576_drawPixel(&hi2c1, initStruct, buffer, 35, 1, 0);
							pcf8576_drawPixel(&hi2c1, initStruct, buffer, 35, 2, 0);
						break;
						
						case (1<<10):	//0400
							pcf8576_drawPixel(&hi2c1, initStruct, buffer, 36, 0, 0);
							pcf8576_drawPixel(&hi2c1, initStruct, buffer, 36, 1, 0);
							pcf8576_drawPixel(&hi2c1, initStruct, buffer, 36, 2, 0);
						break;
						
						case (1<<11):	//0800
							pcf8576_drawPixel(&hi2c1, initStruct, buffer, 37, 0, 0);
							pcf8576_drawPixel(&hi2c1, initStruct, buffer, 37, 1, 0);
							pcf8576_drawPixel(&hi2c1, initStruct, buffer, 37, 2, 0);
							pcf8576_drawPixel(&hi2c1, initStruct, buffer, 37, 3, 0);
						break;
						
						case (1<<12):	//1000
							for(unsigned char i = 30; i <= 33; i++) {
								for(unsigned char j = 0; j < 4; j++) {
									pcf8576_drawPixel(&hi2c1, initStruct, buffer, i, j, 0);
								}
							}
						break;
						
						case (1<<13):	//2000
							for(unsigned char i = 26; i <= 29; i++) {
								for(unsigned char j = 0; j < 4; j++) {
									pcf8576_drawPixel(&hi2c1, initStruct, buffer, i, j, 0);
								}
							}
						break;
						
						case (1<<14):	//4000
							for(unsigned char i = 22; i <= 25; i++) {
								for(unsigned char j = 0; j < 4; j++) {
									pcf8576_drawPixel(&hi2c1, initStruct, buffer, i, j, 0);
								}
							}
						break;
						
						case (1<<15):	//8000
							pcf8576_drawPixel(&hi2c1, initStruct, buffer, 4, 3, 1);
						break;
						
						default:
						break;
					}
				}
				
				
				
				printf("Int OUT\r\n");
				tp_int = 0;
			}

		
		}

	}
	
	
	
  }
  /* USER CODE END 3 */

}

/** System Clock Configuration
*/
void SystemClock_Config(void)
{

  RCC_OscInitTypeDef RCC_OscInitStruct;
  RCC_ClkInitTypeDef RCC_ClkInitStruct;

    /**Initializes the CPU, AHB and APB busses clocks 
    */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = 16;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

    /**Initializes the CPU, AHB and APB busses clocks 
    */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }

    /**Configure the Systick interrupt time 
    */
  HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);

    /**Configure the Systick 
    */
  HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

  /* SysTick_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}

/* I2C1 init function */
static void MX_I2C1_Init(void)
{

  hi2c1.Instance = I2C1;
  hi2c1.Init.ClockSpeed = 400000;
  hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
  hi2c1.Init.OwnAddress1 = 0;
  hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
  hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
  hi2c1.Init.OwnAddress2 = 0;
  hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
  hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
  if (HAL_I2C_Init(&hi2c1) != HAL_OK)
  {
    Error_Handler();
  }

}

/* USART1 init function */
static void MX_USART1_UART_Init(void)
{

  huart1.Instance = USART1;
  huart1.Init.BaudRate = 115200;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }

}

/** Configure pins as 
        * Analog 
        * Input 
        * Output
        * EVENT_OUT
        * EXTI
*/
static void MX_GPIO_Init(void)
{

  GPIO_InitTypeDef GPIO_InitStruct;

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(EN_VDDOUT_GPIO_Port, EN_VDDOUT_Pin, GPIO_PIN_SET);

  /*Configure GPIO pin : EN_VDDOUT_Pin */
  GPIO_InitStruct.Pin = EN_VDDOUT_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(EN_VDDOUT_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : PB5 */
  GPIO_InitStruct.Pin = GPIO_PIN_5;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  /* EXTI interrupt init*/
  HAL_NVIC_SetPriority(EXTI9_5_IRQn, 1, 0);
  //HAL_NVIC_EnableIRQ(EXTI9_5_IRQn);

}

/* USER CODE BEGIN 4 */
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
	tp_int = 1;
}
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @param  None
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler */
  /* User can add his own implementation to report the HAL error return state */
  while(1) 
  {
  }
  /* USER CODE END Error_Handler */ 
}

#ifdef USE_FULL_ASSERT

/**
   * @brief Reports the name of the source file and the source line number
   * where the assert_param error has occurred.
   * @param file: pointer to the source file name
   * @param line: assert_param error line source number
   * @retval None
   */
void assert_failed(uint8_t* file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
    ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */

}

#endif

/**
  * @}
  */ 

/**
  * @}
*/ 

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
